import entity.Person;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author zk
 * @date 2019-10-27 13:35
 */
public class CopyObjectDemo {
    @Test
    public void copyTest() throws InvocationTargetException, NoSuchMethodException, InstantiationException,
            IllegalAccessException {
        Person psn = new Person();
        psn.setAge(18);
        psn.setName("张三");
        psn.setSex("男");

        Object obj = copyObject(psn);
        System.out.println(psn);
        System.out.println(obj);
    }

    public Object copyObject(Object obj) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Constructor constructor = clazz.getDeclaredConstructor();
        Object instance = constructor.newInstance();

        for(Field field: fields){
            field.setAccessible(true);
            field.set(instance,field.get(obj));
        }

        return instance;
    }
}
